from flaskapp.exts import db


class Book(db.Model):
    __tablename__ = 'books'

    bookid = db.Column(db.Integer, primary_key=True)
    bookname = db.Column(db.String(80), nullable=True)
    author = db.Column(db.String(80), nullable=False)
    press = db.Column(db.String(80), nullable=False)
    syn = db.Column(db.Text, nullable=True)
    surplus = db.Column(db.Integer, nullable=False)
    category = db.Column(db.String(80), nullable=True)
    coverpath = db.Column(db.String(80), nullable=True)
    price = db.Column(db.Float, nullable=True)

    def __init__(self, bookname, author, press, surplus, category, coverpath, price):
        self.bookname = bookname
        self.author = author
        self.press = press
        self.surplus = surplus
        self.category = category
        self.coverpath = coverpath
        self.price = price

    def to_dict(self):
        return {
            'bookid': self.bookid,
            'bookname': self.bookname,
            'author': self.author,
            'press': self.press,
            'surplus': self.surplus,
            'syn': self.syn,
            'category': self.category,
            'coverpath': self.coverpath,
            'price': self.price
        }

    def update(self, bookname, author, press, surplus, category,price):
        self.bookname = bookname
        self.author = author
        self.press = press
        self.surplus = surplus
        self.category = category
        self.price = price
        db.session.commit()

    def borrowBook(self):
        self.surplus -= 1
        if self.surplus < 0:
            return False
        else:
            db.session.add(self)
            db.session.commit()
            return True

    def returnBook(self):
        self.surplus += 1
        return True

    def addBook(self):
        db.session.add(self)
        db.session.commit()

    def deleteBook(self):
        db.session.delete(self)
        db.session.commit()
